/**
* std::atomic
*/

#include <atomic>
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>

std::atomic_flag lock = ATOMIC_FLAG_INIT;

std::stringstream stream;

void append_number(int x) {
    while (lock.test_and_set()) {} // 无限循环，直到 atomic_flag 为 true
    stream << "thread#" << x << std::endl;
    lock.clear();
}

int main() {
    std::vector<std::thread> ths;
    for (int i = 0; i < 10; i++) {
        ths.push_back(std::thread(append_number, i));
    }
    for (int i = 0; i < 10; i++) {
        ths[i].join();
    }
    std::cout << stream.str();
    return 0;
}